package com.broada.apm.common.util;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

/**
 * 基于jdom的xml工具类
 * @author Administrator
 * Create By 2012-5-18 下午3:16:56
 */
public class XmlUtil {

  /**
   * 根据文件路径取得文档对象
   * @param filePath
   * @return
   * @throws IOException
   * @throws JDOMException
   */
  public static Document getDoc(String filePath) throws JDOMException, IOException{
    SAXBuilder builder = new SAXBuilder();
    Document doc = null;
    doc = builder.build(new File(filePath));
    return doc;
  }

  /**
   * 遍历文档，得到结点属性的映射关系Map<key,value>
   * @param node 文档遍历开始结点
   * @param map 需要返回的map
   * @param key 需要获取的节点key
   * @param value 需要获取的节点value
   */
  public static void getAttrMap(Element node, Map<String, String> map, String key, String value) {
    List<Element> elementList = node.getChildren();
    for (int i = 0; i < elementList.size(); i++) {
      Element child = (Element) elementList.get(i);
      String _key = child.getAttributeValue(key);
      String _value = child.getAttributeValue(value);
      map.put(_key, _value);
      getAttrMap(child, map, key, value);
    }
  }
  
  /**
   * 遍历文档，得到结点的映射关系Map<key,value>，把父亲节点的条件加到子节点
   * @param node 文档遍历开始结点
   * @param map 需要返回的map
   * @param key 需要获取的节点key
   * @param value 需要获取的节点value
   * @param attr 需要叠加的属性
   */
  public static void getAttrMap(Element node, Map<String, String> map, String key, String value, String attr) {
	  List<Element> elementList = node.getChildren();
	  String _attr = node.getAttributeValue(attr);
	  for (int i = 0; i < elementList.size(); i++) {
		  Element child = (Element) elementList.get(i);
		  String _key = child.getAttributeValue(key);
		  String _value = child.getAttributeValue(value);
		  if(null!=_attr&&!"".equals(_attr.trim())){
			  _value = _attr + _value;
		  }
		  map.put(_key, _value);
		  getAttrMap(child, map, key, value, attr);
	  }
  }
  
}
